<?php require_once 'httpFilter.php'; 'conf.php';?>
<?php
	require_once "services/budgetServices.php";
	require_once 'services/OFXStatementParser.php';
	require_once 'services/FNBCSVStatementParser.php';
	
	$accountName = $_REQUEST["accName"];
	$accountType = $_REQUEST["accountTypeSelect"];
	$availableBal = $_REQUEST["availableAmnt"];
	$uploadFileType = $_REQUEST["uploadStatementType"];
	$budgetStartDate = $_REQUEST["budgetStartDate"];
	$uploadFileName = $_FILES['transactionFile']['tmp_name'];
	$userId = $_SESSION["userid"];
	$errCode = 0;	
	$statement = null;
	
	$statementBalance = 0;
	$accountNumber = "";
	$openingBal = 0;
	
	if(strcmp($uploadFileType,"CSV") == 0){
		//hashkey already uses accountId as part of the hash in the csv upload, must keep supporting this to avoid duplicates
		$statement = new FNBCSVStatementParser();
		
		//create the account
		$accountId = createAccount($accountName,$accountNumber,$accountType,$availableBal,$budgetStartDate,$statementBalance,$openingBal,$userId);
		$statement->accountId = $accountId;
		
		//get the statement
		$statement->loadFromFile($uploadFileName);
		
		$bankDetails = (array)$statement->getBankAcctDetails();
		$accountNumber = $bankDetails["AccountNumber"];
		$statementBalance = $statement->getStatementBalance();
		$availableBal = $statement->getAvailableBalance();
		$openingBal = getOpeningBalance($statement);
		
		//update the account details
		updateAccountDetails($accountName,$accountNumber,$accountId,$accountType,$statementBalance,$availableBal,$openingBal);
	}
	else{
		//dont need accountId for hash, so allows single call to accounts table
		$statement = new OFXStatementParser();
		$statement->loadFromFile($uploadFileName);
		
		$bankDetails = (array)$statement->getBankAcctDetails();
		$accountNumber = $bankDetails["AccountNumber"];
		
		$statementBalance = $statement->getStatementBalance();
		if(strlen($availableBal) == 0){
			$availableBal = $statementBalance;			
		}
		$openingBal = getOpeningBalance($statement);
		$accountId = createAccount($accountName,$accountNumber,$accountType,$availableBal,$budgetStartDate,$statementBalance,$openingBal,$userId);
	}	
	
	uploadStatement($statement,$accountId);
	
	if($errCode == 0){
		echo "<result>";
		echo "<code>";
		echo $errCode;
		echo "</code>";
		echo "</result>";
	}
	
	
	function getOpeningBalance($statement){
		$totalTransactions = 0;
		foreach($statement->getTransactions() as $transaction){
			$totalTransactions = $totalTransactions + $transaction->getTranAmount();
		}
		$openingBal = $statement->getStatementBalance() + ($totalTransactions * -1);
		return $openingBal;
	}
	
	
	function createAccount($accountName,$accountNumber,$accountType,$availableBal,$budgetStartDate,$statementBalance,$openingBal,$userId){
		$budgetService = new BudgetService;
		//Create Account first.
		$parameters = array();
		$parameters["accountName"] = $accountName;
		$parameters["accountNum"] = $accountNumber;
		
		if(strlen($accountType) == 0){
			$accountType = "normal";
		}
		$parameters["openingBal"] = $openingBal;
		$parameters["accountType"] = $accountType;
		$parameters["statementBalance"] = $statementBalance;
		$parameters["availableBal"] = $availableBal;
		$parameters["userid"] = $userId;
		
		$budgetService->createAccount($parameters);
		$accountId = $budgetService->getFirstTransactionalAccountId($userId);
		$budgetService->setStartOfMonthDate($budgetStartDate, $userId);
		
		return $accountId;
	}
	
	
	function uploadStatement($statement,$accountId){
		$count = 0;
		$hashkeyFound = false;
		
		foreach($statement->getTransactions() as $transaction){
			$count = $count + $transaction->getTranAmount();
				
			try {
				$date = $transaction->getTranDate();
				$bankref = trim($transaction->getTranDescription());
				$hashkey = trim($transaction->getTranHash());
		
				$con = new PDO(GlobalConfig::db_pdo_connect_string, GlobalConfig::db_username, GlobalConfig::db_password);
				//$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
				$query = "insert into transaction (accountId, date, amount, description, reconciled, categoryId, bankRef, hashkey) values (:accId, :date, :amount, '', 0, 0, :bankRef, :hashkey)";
				$stmt = $con->prepare($query);
				$stmt->bindParam(':accId', $accountId);
				$stmt->bindParam(':date', $date);
				$stmt->bindParam(':amount', $transaction->getTranAmount());
				$stmt->bindParam(':bankRef', $bankref);
				$stmt->bindParam(':hashkey', $hashkey);
		
				if (!$stmt->execute()){
					error_log("COULD NOT SAVE TRANSACTION");
				}
		
			} catch(PDOException $e){
				error_log($e->getMessage());
				print "Error!: " . $e->getMessage() . "<br/>";
				die();
					
				$errCode = $e->getMessage();
				$errorCodes = new ErrorCodes;
				$errMessage = $errorCodes->getErrorMessage($e->getMessage());
		
				error_log("Error Message: " . $errMessage);
				echo "<result>";
				echo "<code>";
				echo $errCode;
				echo "</code>";
				echo "<errMessage>";
				echo $errMessage;
				echo "</errMessage>";
				echo "</result>";
				break;
			}
		}
	}
	
	
	function updateAccountDetails($accountName,$accountNumber,$accountId,$accountType,$statementBalance,$availableBal,$openingBal){
		$parameters = array();
		$parameters["accountNum"] = $accountNumber;
		$parameters["accountId"] = $accountId;
		$parameters["accountType"] = $accountType;
		$parameters["statementBalance"] = $statementBalance;
		$parameters["availableBal"] = $availableBal;
		$parameters["openingBal"] = $openingBal;
		$parameters["accountName"] = $accountName;
		$parameters["active"] = 1;
		
		$budgetService = new BudgetService;
		$budgetService->updateAccountDetails($parameters);
	}
?>